# models.py

from sqlalchemy import Column, Integer, String, Date, ForeignKey, Text, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from datetime import date
from backend.database.session import Base, engine  # 修改为绝对导入

# 用户表
class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False)
    password_hash = Column(String(128), nullable=False)
    role = Column(String(20), default="doctor")  # 添加角色字段，默认为普通医生
    doctor_name = Column(String(50), unique=True, nullable=True)  # 医生名称，唯一
    
    records = relationship("FollowUpRecord", back_populates="user")

# 随访记录主表
class FollowUpRecord(Base):
    __tablename__ = "follow_up_records"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), ForeignKey("users.username"), nullable=False)
    doctor_name = Column(String(50), nullable=False)
    date = Column(Date, default=date.today)
    left_eye_image = Column(String(255))  # 左眼图片路径
    right_eye_image = Column(String(255))  # 右眼图片路径
    # 移除android_data字段

    user = relationship("User", back_populates="records")
    diagnoses = relationship("Diagnosis", back_populates="record", cascade="all, delete-orphan")
    advices = relationship("Advice", back_populates="record", cascade="all, delete-orphan")

# 诊断表
class Diagnosis(Base):
    __tablename__ = "diagnoses"

    id = Column(Integer, primary_key=True, index=True)
    record_id = Column(Integer, ForeignKey("follow_up_records.id"))
    name = Column(String(50))         # 疾病名称，如糖尿病、青光眼等
    risk_level = Column(String(10))   # 风险等级：高危、中危、低危

    record = relationship("FollowUpRecord", back_populates="diagnoses")

# 建议表
class Advice(Base):
    __tablename__ = "advices"

    id = Column(Integer, primary_key=True, index=True)
    record_id = Column(Integer, ForeignKey("follow_up_records.id"))
    source = Column(String(50))      # 来源：如 deepseek、华佗
    content = Column(Text)           # 纯文字内容，支持 UTF-8

    record = relationship("FollowUpRecord", back_populates="advices")

# 删除重复的数据库连接代码
# 创建数据库连接和 Session
# DATABASE_URL = "sqlite:///./followup.db"  # 可替换为 mysql://user:pwd@localhost/dbname

# engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 用于创建表结构
def init_db():
    Base.metadata.create_all(bind=engine)
